using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Rapier.Kodachi.Shared;

namespace Rapier.Kodachi.Weather
{
    public partial class LocationSelection : Form
    {
        private Host host;

        private DataRow _SelectedRow;
        public DataRow SelectedRow
        {
            get { return _SelectedRow; }
        }
	
        
        public LocationSelection(Host host, DataSet weatherLocations)
        {
            InitializeComponent();
            this.host = host;

            gridSelections.DoubleClick += new EventHandler(gridSelections_DoubleClick);
            gridSelections.KeyDown += new KeyEventHandler(gridSelections_KeyDown);

            try
            {
                BindingSource binding = new BindingSource(weatherLocations, "loc");
                gridSelections.DataSource = binding;
                gridSelections.Columns["loc_Text"].HeaderText = "Locations";
                gridSelections.Columns["loc_Text"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                gridSelections.Columns["type"].Visible = false;
                gridSelections.Columns["id"].Visible = false;
            }
            catch
            {
                gridSelections.Rows.Clear();
                gridSelections.Columns.Clear();
                gridSelections.ReadOnly = true;

                NotificationPackage package = new NotificationPackage();
                package.Message = "Error loading weather location selections...";
                package.Caption = "Error loading selections...";
                host.Notify(package);               
            }
        }

        void gridSelections_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SetSelectedRow();
                e.Handled = true;
            }
        }

        void gridSelections_DoubleClick(object sender, EventArgs e)
        {
            SetSelectedRow();
        }

        private void bOk_Click(object sender, EventArgs e)
        {
            SetSelectedRow();
        }

        private void SetSelectedRow()
        {
            if (gridSelections.SelectedRows.Count == 1)
            {
                _SelectedRow = (gridSelections.SelectedRows[0].DataBoundItem as DataRowView).Row;
                this.DialogResult = DialogResult.OK;
                Close();
            }
            else
            {
                _SelectedRow = null;
                this.DialogResult = DialogResult.None;
            }
        }

        private void bCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            _SelectedRow = null;
            Close();
        }
    }
}